package com.zansc.longd.service.impl.s;

import com.zansc.longd.config.shiro.ShiroToken;
import com.zansc.longd.domain.entity.s.User;
import com.zansc.longd.domain.mapper.s.UserMapper;
import com.zansc.longd.exception.ServiceException;
import com.zansc.longd.model.base.in.UserIn;
import com.zansc.longd.model.code.ErrorCode;
import com.zansc.longd.service.s.UserService;
import com.zansc.longd.utils.JWTUtils;
import com.zansc.longd.utils.MD5Utils;
import com.zansc.longd.utils.SaltUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(UserIn userIn) {
        User user = new User();
        user.setUsername(userIn.getUsername());
        user.setNickname(userIn.getNickname());
        user.setPhone(userIn.getPhone());
        user.setSex(userIn.getSex());
        String salt = SaltUtils.getSalt(16);
        user.setSalt(salt);
        user.setPassword(MD5Utils.md5Encryption(userIn.getPassword(), salt));
        user.setCreateTime(LocalDateTime.now());
        user.setBirth(LocalDateTime.ofEpochSecond(userIn.getBirth(), 0, ZoneOffset.ofHours(8)));
        user.setUserRemark(userIn.getUser_remark());
        user.setAreaId(userIn.getArea_id());
        user.setType(1);
        user.setStatus(0);
        userMapper.insert(user);
    }
    
    @Override
    public User findUserByName(String username) {
        User user = new User();
        user.setUsername(username);
        return userMapper.selectOne(user);
    }
    
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }
    
    @Override
    public User selectByPrimaryKey(int id) {
        return userMapper.selectByPrimaryKey(id);
    }
    
    @Override
    public int updateByPrimaryKey(User id) {
        return userMapper.updateByPrimaryKey(id);
    }
    
    @Override
    public String login(String username, String password) {
        String token;
        User userByName = findUserByName(username);
        if (userByName != null) {
            String salt = userByName.getSalt();
            String tg = MD5Utils.md5Encryption(password, salt);
            token = JWTUtils.sign(username, tg);
            ShiroToken shiroToken = new ShiroToken(token);
            try {
                SecurityUtils.getSubject().login(shiroToken);
            } catch (AuthenticationException e) {
                throw new ServiceException(ErrorCode.NOT_PASSWORD);
            }
        } else {
            throw new ServiceException(ErrorCode.NOT_USERNAME);
        }
        return token;
    }
    
}
